#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<unordered_map>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

int pathSum(TreeNode* root, int targetSum) {
    if (!root)   return 0;
    int res = rootSum(root, targetSum);
    res += pathSum(root->left, targetSum);
    res += pathSum(root->right, targetSum);
    return res;
}
int rootSum(TreeNode* root, long long targetSum)
{
    if (!root)   return 0;
    int res = 0;
    if (root->val == targetSum)  res++;
    res += rootSum(root->left, targetSum - root->val);
    res += rootSum(root->right, targetSum - root->val);
    return res;
}

int pathSum(TreeNode* root, int targetSum) {
    int res = 0;
    unordered_map<long long, int> cnt{ {0,1} };
    auto dfs = [&](this auto&& dfs, TreeNode* root, long long s) {
        if (root == nullptr) return;

        s += root->val;
        res += cnt[s - targetSum];
        cnt[s]++;
        dfs(root->left, s);
        dfs(root->right, s);
        cnt[s]--;
    };
    dfs(root, 0);
    return res;
}